package com.qinyi.framework.aspect;

import com.qinyi.common.annotation.DataSource;
import com.qinyi.common.config.DynamicDataSourceContextHolder;
import com.qinyi.common.enums.DataSourceType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author wangan on 2019/6/3
 * @description
 */
@Aspect
@Component
public class DataSourceAspect {

	@Pointcut(value = "@annotation(com.qinyi.common.annotation.DataSource)")
	public void pointCut() {
	}

	@Before(value = "pointCut()")
	public void before(JoinPoint joinPoint) {
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		Method method = methodSignature.getMethod();
		DataSource dataSource = method.getAnnotation(DataSource.class);
		DataSourceType value = dataSource.value();
		if (dataSource != null) {
			DynamicDataSourceContextHolder.setDataSourceType(value.name());
		}
	}
}
